/**
 * Copyright (C) 2018-2020
 * All rights reserved, Designed By www.yixiang.co
 * 注意：
 * 本软件为www.yixiang.co开发研制，未经购买不得使用
 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
 */
package co.yixiang.modules.user.rest;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import co.yixiang.api.ApiResult;
import co.yixiang.api.YshopException;
import co.yixiang.common.bean.LocalUser;
import co.yixiang.common.interceptor.AuthCheck;
import co.yixiang.constant.ShopConstants;
import co.yixiang.enums.BillDetailEnum;
import co.yixiang.enums.BillEnum;
import co.yixiang.modules.pay.AppPayService;
import co.yixiang.modules.shop.domain.YxSystemGroupData;
import co.yixiang.modules.shop.service.YxSystemGroupDataService;
import co.yixiang.modules.shop.service.dto.YxSystemGroupDataQueryCriteria;
import co.yixiang.modules.shop.vo.YxSystemGroupDataVo;
import co.yixiang.modules.user.domain.YxUser;
import co.yixiang.modules.user.domain.YxUserBill;
import co.yixiang.modules.user.domain.YxUserRecharge;
import co.yixiang.modules.user.service.YxUserBillService;
import co.yixiang.modules.user.service.YxUserRechargeService;
import co.yixiang.mp.service.WeixinPayService;
import co.yixiang.utils.RandonOrderNoUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户充值 前端控制器
 * </p>
 *
 * @author hupeng
 * @since 2020-03-01
 */
@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Api(value = "用户充值", tags = "用户:用户充值", description = "用户充值")
public class UserRechargeController {

    private final YxSystemGroupDataService systemGroupDataService;
    private final WeixinPayService weixinPayService;
    private final AppPayService appPayService;
    private final YxUserBillService yxUserBillService;
    private final YxUserRechargeService userRechargeService;

    /**
     * 充值方案
     */
    @GetMapping("/recharge/index")
    @ApiOperation(value = "充值方案",notes = "充值方案",response = ApiResult.class)
    public ApiResult<Object> getWays(){
        YxSystemGroupDataQueryCriteria queryCriteria = new YxSystemGroupDataQueryCriteria();
        queryCriteria.setGroupName(ShopConstants.YSHOP_RECHARGE_PRICE_WAYS);
        List<YxSystemGroupData> yxSystemGroupDataList = systemGroupDataService.queryAll(queryCriteria);

        List<YxSystemGroupDataVo> systemGroupDataVoList = yxSystemGroupDataList.stream().map(s->{
            YxSystemGroupDataVo systemGroupDataVo = new YxSystemGroupDataVo();
            BeanUtil.copyProperties(s,systemGroupDataVo,"value");
            systemGroupDataVo.setValue(JSON.parseObject(s.getValue()));
            return systemGroupDataVo;
        }).collect(Collectors.toList());

        Map<String,Object> map = new LinkedHashMap<>();
        map.put("recharge_price_ways",systemGroupDataVoList);
        return ApiResult.ok(map);
    }


    /**
     * 充值
     */
    @AuthCheck
    @GetMapping("/recharge/money")
    @ApiOperation(value = "充值金额",notes = "充值金额",response = ApiResult.class)
    public ApiResult rechargeMoney(@RequestParam("money")BigDecimal money, @RequestParam("type")Integer type,
                                   @RequestParam(value = "payImage",required = false) String payImage, HttpServletRequest request){

       /* throw new YshopException("未开放");*/
        YxUser user = LocalUser.getUser();
        if(null==money || new BigDecimal(0).compareTo(money)>=0){
            throw new YshopException("充值金额应大于0");
        }
//        if (ObjectUtil.isEmpty(payImage)) throw new YshopException("请上传支付凭证");
        String orderId = "recharge"+ IdWorker.getId();
        YxUserRecharge userRecharge = new YxUserRecharge();
        userRecharge.setUid(user.getUid());
        userRecharge.setPrice(money);
        userRecharge.setPayImage(payImage);
        userRecharge.setPayTime(new Date());
        userRecharge.setRechargeType(String.valueOf(type));
        userRecharge.setPaid(0);
        userRecharge.setOrderId(orderId);
        userRecharge.setApprovalStatus(1);
        userRechargeService.save(userRecharge);
//        return ApiResult.ok("充值成功");
//
//        //充值流水入库
//        YxUserBill userBill = YxUserBill.builder()
//                .uid(user.getUid())
//                .title("充值")
//                .category(BillDetailEnum.CATEGORY_1.getValue())
//                .type(BillDetailEnum.TYPE_1.getValue())
//                .number(money)
//                .balance(user.getNowMoney())
//                .mark("充值")
//                .payType(type)
//                .status(0)
//                .orderNo("chongzhi"+RandonOrderNoUtil.getOrderIdByTime())
//                .pm(BillEnum.PM_1.getValue())
//                .isPay(0)
//                .build();
//        yxUserBillService.save(userBill);
        return ApiResult.ok(appPayService.payment(request,type,userRecharge.getOrderId(),money));
    }

    /** 充值 */
    @AuthCheck
    @GetMapping("/appletRecharge/money")
    @ApiOperation(value = "小程序充值金额",notes = "小程序充值金额",response = ApiResult.class)
    public ApiResult appletRechargeMoney(@RequestParam("money") BigDecimal money, HttpServletRequest request){
        YxUser user = LocalUser.getUser();
        if(null==money || new BigDecimal(0).compareTo(money)>=0){
            throw new YshopException("充值金额应大于0");
        }

        String orderId = "recharge"+IdWorker.getId();
        YxUserRecharge userRecharge = new YxUserRecharge();
        userRecharge.setUid(user.getUid());
        userRecharge.setPrice(money);
        userRecharge.setRechargeType(String.valueOf(2));
        userRecharge.setPaid(0);
        userRecharge.setOrderId(orderId);
        userRechargeService.save(userRecharge);

        Map<String,String> jsConfig = new HashMap<>();
        WxPayMpOrderResult wxPayMpOrderResult = (WxPayMpOrderResult)weixinPayService
                .unifyPay(orderId,"routine", BillDetailEnum.TYPE_1.getValue(),"小程序充值");
        jsConfig.put("appId",wxPayMpOrderResult.getAppId());
        jsConfig.put("timeStamp",wxPayMpOrderResult.getTimeStamp());
        jsConfig.put("paySign",wxPayMpOrderResult.getPaySign());
        jsConfig.put("nonceStr",wxPayMpOrderResult.getNonceStr());
        jsConfig.put("package",wxPayMpOrderResult.getPackageValue());
        jsConfig.put("signType",wxPayMpOrderResult.getSignType());

        return ApiResult.ok(jsConfig);
    }

}

